package com.qxzn.app.page;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.qxzn.app.page.util.JavaScriptInteraction;
import com.qxzn.app.util.AppUtil;

import butterknife.BindView;

/**
 * Created by Administrator on 2017/6/19.
 */
public class WebActivity extends BaseActivity {
    @BindView(R2.id.webView)
    WebView webView;
    @BindView(R2.id.progressBar)
    ProgressBar progressBar;
    //    @BindView(R.id.ll_root)
//    LinearLayout llRoot;
    private String title, html, url;
    private String carId;
    private WebSettings settings;

    @Override
    protected int initLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
//        webView = new WebView(getApplicationContext());
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        webView.setLayoutParams(params);
//        llRoot.addView(webView);
    }

    @Override
    protected void iniTitleBar() {
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        title = getIntent().getStringExtra("title");
        html = getIntent().getStringExtra("html");
        url = getIntent().getStringExtra("url");
        tv_title.setText(title);
        initEvent();
        loadWebData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        AppUtil.showLog("onNewIntent");
        setIntent(intent);
        initData(null);
    }

    private void initEvent() {
        settings = webView.getSettings();
        settings.setBlockNetworkImage(true);
        //设置WebView属性，能够执行Javascript脚本
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDefaultTextEncodingName("umtf-8");
        settings.setBuiltInZoomControls(true);//是否缩放，默认false，必须设置才能实现缩放
        settings.setDisplayZoomControls(false);//不显示缩放按钮
        //设置可以访问文件
        settings.setAllowFileAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheEnabled(true);//设置缓存为可以用
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.addJavascriptInterface(new JavaScriptInteraction(), "AppInterface");
        //Https和http混合模式，防止http开头的无法图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                if (url == null)
                    return false;
//                if (!TextUtils.isEmpty(view.getTitle()) && !view.getTitle().startsWith("www.") && !view.getTitle().startsWith("http://") && !view.getTitle().startsWith("https://")) {
//                    tvTitle.setText(view.getTitle());
//                }
                AppUtil.showLog("title:" + view.getTitle() + "---shouldOverrideUrlLoading：" + url);
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                } else {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                        e.printStackTrace();
                    }
                    return true;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                if (!TextUtils.isEmpty(view.getTitle()) && !view.getTitle().startsWith("www.") && !view.getTitle().startsWith("http://") && !view.getTitle().startsWith("https://")) {
//                    tvTitle.setText(view.getTitle());
//                }
                AppUtil.showLog("title:" + view.getTitle() + "---onPageFinished：" + url);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                    settings.setBlockNetworkImage(false);
                }
//                if (newProgress == 100) {
//                    // 网页加载完成1
//                    hideProgress();
//                } else {
//                    // 加载中
//                    showProgress();
//                }

            }
        });

    }

    public void loadWebData() {
        if (html != null) {
            String encoding = "UTF-8";
            String mimeType = "text/html";
            webView.loadDataWithBaseURL("", html, mimeType, encoding, "about:blank");
        } else {
            AppUtil.showLog("title:" + webView.getTitle() + "---url:" + url);
            webView.loadUrl(url);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }

            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();
            webView.setVisibility(View.GONE);//防止ZoomControls还没有消失是页面关闭导致crash
            try {
                webView.destroy();
            } catch (Throwable ex) {

            }
            webView = null;
        }
        super.onDestroy();
    }

}
